import React, { useState, useRef, useEffect } from 'react';
import { NavBar, Button, Cell, Tag, CellGroup, Popup, Input, Sticky } from '@nutui/nutui-react'
import '@nutui/nutui-react/dist/style.css'
import styles from './order.module.css'
import { Toast } from 'react-vant'
import { ArrowLeft, Clock, CheckNormal, User, Phone, Check, ArrowRight, ArrowUp } from '@nutui/icons-react'
import axios from 'axios';
import { useLocation, useNavigate } from 'react-router-dom';
const Order = () => {

    const alipayForm = useRef(null)
    const [showIconPosition, setShowIconPosition] = useState(false)
    const [showBottomRound1, setShowBottomRound1] = useState(false)
    const [selectedTime, setSelectedTime] = useState('20:00');
    const [showTimePopup, setShowTimePopup] = useState(false);
    const [phone, setPhone] = useState('')
    const [name, setName] = useState('')
    const [startDay, setStart] = useState()
    const [endDay, setEnd] = useState()
    // 新增状态
    const [useEnvironmentalOption, setUseEnvironmentalOption] = useState(false);
    const [selectedPayment, setSelectedPayment] = useState('会员卡支付');
    const [benefitSelections, setBenefitSelections] = useState({
        coupon: true,
        lateCheckout: true
    });
    const timeOptions = [
        '20:00', '21:00', '22:00',
        '23:00', '次日00:00', '次日01:00',
        '次日02:00', '次日03:00', '次日04:00',
        '次日05:00', '次日06:00'
    ];

    // 支付方式配置数据
    const paymentOptions = [
        {
            id: '会员卡支付',
            color: '#FFC300',
            name: '会员卡支付',
            badge: '优惠',
            // desc: '立减¥10'
        },
        {
            id: '支付宝支付',
            color: '#1677FF',
            name: '支付宝支付',
            // desc: '随机立减最高99元'
        },
        {
            id: '余额支付',
            color: '#8a8de9',
            name: '余额支付',
            // desc: '当前余额: ¥158.50'
        }
    ];
    const handleTimeSelect = (time) => {
        setSelectedTime(time);
        setShowBottomRound1(false);
    };

    // 获取路由信息
    const location = useLocation()
    const val = location.state
    // console.log(val, 11111111);
    console.log(val)
    // if(val.jument  == '徐铭颢'){
        // setSelectedPayment(val.val.pay )
    // }

    const reverseData = localStorage.getItem("reverse");
    const parsedData = JSON.parse(reverseData); // 解析 JSON 字符串
    const nights = parsedData.nights;


    // 修改时间类型
    const DateObj = (dataStr) => {
        const month = parseInt(dataStr.split('月')[0])
        const day = parseInt(dataStr.split('月')[1].replace('日'))
        const dataObj = new Date(new Date().getFullYear(), month - 1, day)
        return dataObj
    }

    const startDate = DateObj(val.start)
    const endDate = DateObj(val.end)
    // console.log(startDate, endDate)
    const [pricelist, setpricelist] = useState([])

    const navigate = useNavigate()
    const getvipprice = () => {
        axios.get(`http://localhost:3010/vipPrice`).then(res => {
            // console.log(res.data.price);
            setpricelist(res.data.price)

        })
    }

    useEffect(() => {
        getvipprice()
        // location.getItem("hotelName",)
    }, [])
    // 添加订单
    const addOrder = async () => {

        if (selectedPayment == '会员卡支付') {
            let list = pricelist.find(e => e.cid == localStorage.getItem('id'))
            console.log(list);
            axios.post(`http://localhost:3010/vipPriceEdit`, { _id: list._id, price: list.price - val.val.price }).then(res => {
                if (res.status == 200) {

                    Toast.success('支付成功')
                    navigate('/tabber/first')
                }

            })
        } else {
            let res = await axios.post('http://localhost:3010/alipay', { price: val.val.price, name: "酒店订单" });

            alipayForm.current.innerHTML = res.data;
            // 主动调用form表单
            // document.forms 获取当前页面所有的表单集合
            document.forms[0].submit();
            // console.log(res);

        }
        console.log(selectedPayment);

        let a = Math.floor(Math.random() * 16)
        let b = new Date()
        // let c = b.setDate(b.getDate() + 1)

        // console.log(a, b, c)
        await axios.post('http://localhost:3010/addorder', {
            start: DateObj(val.start),
            end: DateObj(val.end),
            name: name,
            phone: phone,
            day: Math.floor(Math.random() * 16),
            status: 0,
            price: val.val.price,
            hname: val.title,
            room: val.val.name,
            pay: selectedPayment
        })
            .then(res => {
                if (res.data.code == 200) {
                    // alert('提交成功')

                    navigate("/tabber/first")
                }
            })

    }


    return (
        <div>
            <div ref={alipayForm}>{/* form表单 */}</div>
            <div className={styles.header}>
                <NavBar
                    back={
                        <>
                            <ArrowLeft />
                        </>
                    }
                    onBackClick={() => navigate('/reverse')}
                // title={val.title}
                >
                    {
                        val.jument == '李金雨' &&
                        <span style={{ color: 'white' }}>{val.title}</span>
                    }
                    {
                        val.jument == '徐铭颢' &&
                        <span style={{ color: 'white' }}>{val.val.hname}</span>
                    }
                </NavBar>

            </div>

            {/* 房间预订信息卡片 */}
            <div className={styles.roomBookingCard}>
                {/* 日期选择部分 */}
                <div className={styles.dateSelector}>
                    <div className={styles.dateInfo}>
                        {
                            val.jument == '李金雨' &&
                            <div className={styles.startDate}>
                                <div className={styles.dateNumber}>{val.start}</div>
                                {/* <div className={styles.dateText}>今天</div> */}
                            </div>
                        }
                        {
                            val.jument == '徐铭颢' &&
                            <div className={styles.startDate}>
                                <div className={styles.dateNumber}>{val.val.start}</div>
                                {/* <div className={styles.dateText}>今天</div> */}
                            </div>
                        }
                        <div className={styles.stayNights}>
                            <div className={styles.nightsTag}>{nights}晚</div>
                        </div>
                        {
                            val.jument == '李金雨' &&
                            <div className={styles.endDate}>
                                <div className={styles.dateNumber}>{val.end}</div>
                                {/* <div className={styles.dateText}>明天</div> */}
                            </div>
                        }
                        {
                            val.jument == '徐铭颢' &&
                            <div className={styles.endDate}>
                                <div className={styles.dateNumber}>{val.val.end}</div>
                                {/* <div className={styles.dateText}>明天</div> */}
                            </div>
                        }

                    </div>
                    <div className={styles.roomDetailsLink}>
                        房型详情 &gt;
                    </div>
                </div>

                {/* 房间类型信息 */}
                <div className={styles.roomTypeInfo}>
                    {
                        val.jument == '李金雨'
                        &&
                        <div className={styles.roomTitle}>{val.val.name}</div>
                    }
                    {
                        val.jument == '徐铭颢'
                        &&
                        <div className={styles.roomTitle}>{val.val.room}</div>
                    }
                    <div className={styles.roomFeatures}>
                        <div className={styles.featureItem}>大床</div>
                        <div className={styles.featureItem}>2份早餐</div>
                        <div className={styles.featureItem}>2人入住</div>
                        <div className={styles.featureItem}>{val.val.area}m²</div>
                        <div className={styles.featureItem}>有窗</div>
                        <div className={styles.featureItem}>可吸烟</div>
                    </div>
                </div>

                {/* 房间政策信息 */}
                <div className={styles.roomPolicies}>
                    <div className={styles.policyItem}>
                        <Clock className={styles.policyIcon} />
                        <span className={styles.policyText}>30分钟内可免费取消</span>
                    </div>
                    <div className={styles.policyItem}>
                        <CheckNormal className={styles.policyIcon} />
                        <span className={styles.policyText}>可获快捷认订单</span>
                    </div>
                </div>

                {/* 预订限制提示 */}
                <div className={styles.bookingFooter}>
                    <div className={styles.bookingRestriction}>
                        仅接待持有中国内地签发的有效居民身份证的旅人
                    </div>
                    <span className={styles.roomDetailsLink} onClick={() => {
                        setShowIconPosition(true)
                    }}>
                        订购必读 &gt;
                    </span>
                </div>

            </div>
            <Popup
                closeable
                visible={showIconPosition}
                closeIconPosition="top-right"
                position="bottom"
                onClose={() => {
                    setShowIconPosition(false)
                }}
            >
                <div className={styles.popupContainer}>
                    <div className={styles.popupItem}>
                        <div className={styles.popupLabel}>适用人群</div>
                        <div className={styles.popupValue}>仅接待持有中国内地签发的有效居民身份证的客人</div>
                    </div>

                    <div className={styles.popupItem}>
                        <div className={styles.popupLabel}>预订提示</div>
                        <div className={styles.popupValue}>
                            <div className={styles.popupBullet}>• 您填写的预订信息和联系方式是商家或供应商提供相关服务所需的必要信息，美团会基于履约必要的目的和范围向商家或供应商提供</div>
                            <div className={styles.popupBullet}>• 如您预订的产品涉及实名制要求（如包含有实名制需求的景区门票产品的），需要您填写出行人真实准确的证件信息，用于出游时的身份验证。美团会基于履约必要的目的和范围向供应商提供</div>
                            <div className={styles.popupBullet}>• 订单需等商家或供应商确认后才生效，订单确认结果以美团短信或邮件通知为准；请在订单生效后再至商家前台办理入住</div>
                            <div className={styles.popupBullet}>• 业务实际运营和相应责任由门店入驻签约主体公司负责</div>
                        </div>
                    </div>

                    <div className={styles.popupItem}>
                        <div className={styles.popupLabel}>入离时间</div>
                        <div className={styles.popupValue}>入住时间12:00以后 离店时间12:00以前，如需提前入住或延迟退房请联系商家</div>
                    </div>

                    <div className={styles.popupItem}>
                        <div className={styles.popupLabel}>宠物携带</div>
                        <div className={styles.popupValue}>不允许携带宠物</div>
                    </div>

                </div>
            </Popup>
            <div className={styles.checkInInfoCard}>
                <div className={styles.sectionTitle}>入住信息</div>

                <div className={styles.infoItem}>
                    <div className={styles.infoLabel}>房间数量</div>
                    <div className={styles.infoValue}>1间（每间最多住2人）</div>
                </div>

                <div className={styles.infoItem}>
                    <div className={styles.infoLabel}>
                        住客姓名
                        <span className={styles.infoTip}>?</span>
                    </div>
                    {
                        val.jument == '李金雨' &&
                        <div className={styles.infoValueWithIcon}>
                            <Input placeholder='请输入姓名' value={name} onChange={(e) => setName(e)}></Input>
                            <User />
                        </div>
                    }
                    {
                        val.jument == '徐铭颢' &&
                        <div className={styles.infoValueWithIcon}>
                            <Input placeholder='请输入姓名' value={val.val.name} onChange={(e) => setName(e)}></Input>
                            <User />
                        </div>
                    }
                </div>

                <div className={styles.infoItem}>
                    <div className={styles.infoLabel}>联系手机</div>
                    <div className={styles.infoValueWithIcon}>
                        <div className={styles.phoneArea}>
                            <span className={styles.phoneCode}>86</span>
                            <span className={styles.codeArrow}></span>
                        </div>
                        {
                            val.jument == '李金雨' &&
                            <div style={{display:"flex"}}>
                                <Input placeholder='请输入手机号' value={phone} onChange={(e) => setPhone(e)}></Input>
                                <Phone />
                            </div>
                        }
                        {
                            val.jument == '徐铭颢' &&
                            <div style={{display:"flex"}}>
                                <Input placeholder='请输入手机号' value={val.val.phone} onChange={(e) => setPhone(e)}></Input>
                                <Phone /> 
                            </div>
                        }
                    </div>
                </div>

                <div className={styles.infoItem}>
                    <div className={styles.infoLabel}>预计到店</div>
                    <div className={styles.infoValueWithArrow} onClick={() => {
                        setShowBottomRound1(true)
                    }}>
                        <span>{selectedTime}</span>
                        <span className={styles.infoDesc}>房间将整晚保留</span>
                        <span className={styles.arrowRight}></span>
                    </div>
                </div>
            </div>
            {/* 会员优惠卡片 - 新增 */}
            <div className={styles.memberCard}>
                <div className={styles.memberHeader}>
                    {/* 顶部提示横幅 */}
                    {/* <div className={styles.warningBanner}>
                        客房紧张, 该客房仅剩最后3间，请尽快下单......
                    </div> */}

                    {/* 会员标识 */}
                    <div className={styles.memberTitle}>
                        <span className={styles.goldIcon}>🏆</span>
                        <span className={styles.memberText}>黄金会员</span>
                        <div className={styles.starRating}>
                            <span className={styles.star}>★</span>
                            <span className={styles.star}>★</span>
                            <span className={styles.star}>★</span>
                            <span className={styles.star}>★</span>
                            <span className={styles.star}>★</span>
                        </div>
                    </div>
                </div>

                {/* 可享优惠行 */}
                {/* <div className={styles.discountRow}>
                    <div className={styles.discountLabel}>可享优惠</div>
                    <div className={styles.discountTag}>已享最大优惠</div>
                    <div className={styles.discountAmount}>
                        减¥8.8
                        <ArrowRight className={styles.iconSmall} />
                    </div>
                </div> */}

                {/* 可享权益行 */}
                <div className={styles.benefitsRow}>
                    <div className={styles.benefitsLabel}>
                        可享权益
                        <span className={styles.questionCircle}>?</span>
                    </div>
                </div>

                {/* 权益列表 */}
                <div className={styles.benefitsList}>
                    {/* 第一个权益项 */}
                    <div className={styles.benefitItem}>
                        <div className={styles.benefitText}>
                            <span className={styles.benefitName}>限时送外卖券</span>
                            <span className={styles.benefitDesc}>满40减8元外卖券1张</span>
                        </div>
                        <div className={styles.benefitStatus}>
                            <span className={styles.benefitStatusText}>免费送1份</span>
                            {benefitSelections.coupon}
                        </div>
                    </div>

                    {/* 第二个权益项 */}
                    <div className={styles.benefitItem}>
                        <div className={styles.benefitText}>
                            <span className={styles.benefitName}>延迟退房至14:00</span>
                            <span className={styles.benefitDesc}>安心离店不匆忙</span>
                        </div>

                        <div className={styles.benefitStatus}>
                            <span className={styles.benefitStatusText}>酒店送1份</span>
                            {benefitSelections.lateCheckout}
                        </div>
                    </div>
                </div>

                {/* 积分行 */}
                <div className={styles.pointsRow}>
                    <div className={styles.pointsText}>酒店获酒店积分</div>
                    <div className={styles.pointsAmount}>
                        168积分
                        <span className={styles.pointsDesc}>下次预订可抵</span>
                        <span className={styles.pointsValue}>¥1</span>
                        {/* <ArrowRight className={styles.iconSmall} /> */}
                    </div>
                </div>
            </div>

            {/* 低碳住宿选项 */}
            <div className={styles.ecoCard}>
                <div className={styles.ecoHeader}>
                    <div className={styles.ecoTitle}>低碳住: 助力环保</div>
                    <span className={styles.questionCircle}>?</span>
                </div>

                <div className={styles.ecoContent}>
                    <div className={styles.ecoDesc}>本次入住无需一次性用品，<span style={{ color: 'red' }}>减碳203.2g，酒店积分+200</span></div>
                    <CheckNormal
                        checked={useEnvironmentalOption}
                        onChange={(val) => setUseEnvironmentalOption(val)}
                    />

                </div>
            </div>


            {/* 支付方式卡片 - 修改为三种支付方式 */}
            <div className={styles.paymentCardNew}>
                {paymentOptions.map((option, index) => (
                    <div
                        key={option.id}
                        className={styles.paymentItemNew}
                        onClick={() => setSelectedPayment(option.id)}
                    >
                        <div className={styles.paymentLeftNew}>
                            <div className={styles.paymentInfoNew}>
                                <div className={styles.paymentNameNew}>
                                    {option.name}
                                </div>
                                {/* <div className={styles.paymentDescNew}>{option.desc}</div> */}
                            </div>
                        </div>

                        <div className={styles.paymentRightNew}>
                            {option.discount && (
                                <div className={styles.discountTagNew}>
                                    {option.discount}
                                </div>
                            )}
                            <div
                                className={`${styles.radioButtonNew} ${selectedPayment === option.id ? styles.radioSelectedNew : ''}`}
                            />
                        </div>
                    </div>
                ))}
            </div>

            {/* 发票卡片 - 新增 */}
            <div className={styles.invoiceCard}>
                <div className={styles.invoiceRow}>
                    <span className={styles.invoiceLabel}>发票</span>
                    <div className={styles.invoiceInfo}>
                        入住后在酒店前台领取，发票开具类型与酒店确认
                        {/* <ArrowRight className={styles.iconSmall} /> */}
                    </div>
                </div>
            </div>
            {/* 底部结算栏 */}
            <div className={styles.footerBar}>
                <div className={styles.priceInfo}>
                    <div className={styles.totalPrice}><span>¥{val.val.price}</span></div>
                    {/* <div className={styles.priceDetail}>已优惠 ¥8.8</div> */}
                </div>
                <div className={styles.actionArea}>
                    {/* <span className={styles.moreDetail}>明细 <ArrowUp className={styles.detailArrow} /></span> */}
                    <button className={styles.submitButton} onClick={() => addOrder()}>提交订单</button>
                </div>
            </div>
            <Popup
                visible={showBottomRound1}
                style={{ height: '50%' }}
                position="bottom"
                round
                onClose={() => {
                    setShowBottomRound1(false)
                }}
            >
                <div className={styles.popupContainer}>
                    <div className={styles.popupItem}>
                        <div className={styles.popupTitle}>预计到店</div>
                        <div className={styles.popupDescription}>
                            房间整晚保留，12:00前到店可能要等房，详情请咨询商家
                        </div>

                        <div className={styles.timeGrid}>
                            {timeOptions.map((time) => (
                                <div
                                    key={time}
                                    className={`${styles.timeOption} ${time === selectedTime ? styles.timeSelected : ''}`}
                                    onClick={() => handleTimeSelect(time)}
                                >
                                    {time}
                                </div>
                            ))}
                        </div>
                    </div>
                </div>

            </Popup>
        </div>
    );
};

export default Order;